<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: Wxpay.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\payment;

use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use app\api\model\dao\OrderInfo;
use think\Validate;
use think\Cache;

class Wxpay extends PageBase
{
    private $objOrderInfo;

    public function __construct()
    {
        parent::__construct();
        $this->objOrderInfo = new OrderInfo();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'order_id' => 'require',
        ];
        $msg = [
            'order_id.require' => '订单号必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_NO_AUTH);
        }

        if (isset($param['paybefore'])) {

            // 1、参数校验
            $ret = $this->checkParam($param);
            if ($ret) {
                return $this->getRes(Error::ERR_PARAM, $ret);
            }

            $this->payBefore($param);
        }

        if (isset($param['paynotify'])) {
            echo $this->payNotify($param);
        }

        return $this->getRes();
    }

    public function payBefore($param)
    {
        require_once EXTEND_PATH . 'Wepay/Curl.php';
        require_once EXTEND_PATH . 'Wepay/WeEncryption.php';

        $wxpay_config = config('wxpay_config');
        $app_id = $wxpay_config['app_id'];
        $mch_id = $wxpay_config['mch_id'];
        $app_key = $wxpay_config['app_key'];

        $order_id = $param['order_id'];
        $spbill_create_ip = $param['spbill_create_ip'];


        $body = '订单支付';

        $out_trade_no = $order_id;
        $total_fee = 0;   //付款金额

        $order = $this->objOrderInfo->getOrderInfo($order_id);
        $order_amount = $order['order_amount'];
        $shipping_fee = $order['shipping_fee'];
        $total_fee = $order_amount + $shipping_fee;

        $body = urldecode($body);

        $data = array(
            'body' => $body,
            'out_trade_no' => $out_trade_no,
            'total_fee' => $total_fee,
            'spbill_create_ip' => $spbill_create_ip,
        );

        $encpt = WeEncryption::getInstance($app_id, $mch_id, $app_key);
        $encpt->setNotifyUrl($wxpay_config['we_notify_url']);

        $curl = new Curl();
        $xml_data = $encpt->sendRequest($curl, $data);
        $postObj = $encpt->xmlToObject($xml_data);

    }

    public function payNotify($param)
    {

    }
}
